﻿#include "mainaverageentrustwidget.h"
#include "CommUtil/comfunc.h"
#include<QMessageBox>
#include <qdebug>

MainAverageEntrustWidget::MainAverageEntrustWidget(QWidget *parent) :
    QWidget(parent)
{
    setupViews();
	connect(this,SIGNAL(SigStartTimer(QString ,int)),this,SLOT(SlotStartTimer(QString ,int)));
}

void MainAverageEntrustWidget::setupViews()
{
    layout = new QGridLayout;
    QLabel* accountLabel = new QLabel(QStringLiteral("资金账号"));
    m_accountCombox = new QComboBox;

    QLabel* contractLabel = new QLabel(QStringLiteral("合约"));
    m_contractEdit = new QLineEdit;

    QLabel* bsLabel = new QLabel(QStringLiteral("买卖"));
    m_bsCombox = new QComboBox;
    m_bsCombox->insertItem(0,QStringLiteral("买入"));
    m_bsCombox->insertItem(1,QStringLiteral("卖出"));

    QLabel* ocLabel = new QLabel(QStringLiteral("开平"));
    m_ocCombox = new QComboBox;
    m_ocCombox->insertItem(0,QStringLiteral("开仓"));
    m_ocCombox->insertItem(1,QStringLiteral("平仓"));
    m_ocCombox->insertItem(2,QStringLiteral("平今仓"));

    QLabel* handsLabel = new QLabel(QStringLiteral("每次下单手数"));
    m_HandsSpinBox = new QSpinBox;                       //创建SpinBox
    m_HandsSpinBox->setRange(0, 10000);                              //设置spinBox的值范围
    QLabel* totalhandsLabel = new QLabel(QStringLiteral("总手数"));
    m_TotalHandsSpinBox = new QSpinBox;                       //创建SpinBox
    m_TotalHandsSpinBox->setRange(0, 10000);                              //设置spinBox的值范围
    QLabel* timeLabel = new QLabel(QStringLiteral("时间间隔(秒)"));
    m_timeEdit = new QLineEdit;
    m_OrderTypeCheckbox = new QCheckBox(QStringLiteral("套保"));
    m_ConfirmButton = new QPushButton(QStringLiteral("确定"));

    accountLabel->setFixedWidth(80);
    m_accountCombox->setFixedWidth(100);
    contractLabel->setFixedWidth(80);
    m_contractEdit->setFixedWidth(100);
    bsLabel->setFixedWidth(80);
    m_bsCombox->setFixedWidth(100);
    ocLabel->setFixedWidth(80);
    m_ocCombox->setFixedWidth(100);
    handsLabel->setFixedWidth(80);
    m_HandsSpinBox->setFixedWidth(100);
    totalhandsLabel->setFixedWidth(80);
    m_TotalHandsSpinBox->setFixedWidth(100);
    timeLabel->setFixedWidth(80);
    m_timeEdit->setFixedWidth(100);
    m_OrderTypeCheckbox->setFixedWidth(80);
    m_ConfirmButton->setFixedWidth(80);

    layout->addWidget(accountLabel,0,0,1,1);
    layout->addWidget(m_accountCombox,1,0,1,1);
    layout->addWidget(contractLabel,0,1,1,1);
    layout->addWidget(m_contractEdit,1,1,1,1);
    layout->addWidget(bsLabel,0,2,1,1);
    layout->addWidget(m_bsCombox,1,2,1,1);
    layout->addWidget(ocLabel,0,3,1,1);
    layout->addWidget(m_ocCombox,1,3,1,1);
    layout->addWidget(handsLabel,0,4,1,1);
    layout->addWidget(m_HandsSpinBox,1,4,1,1);
    layout->addWidget(totalhandsLabel,0,5,1,1);
    layout->addWidget(m_TotalHandsSpinBox,1,5,1,1);
    layout->addWidget(timeLabel,0,6,1,1);
    layout->addWidget(m_timeEdit,1,6,1,1);
    layout->addWidget(m_OrderTypeCheckbox,1,7,1,1);
    layout->addWidget(m_ConfirmButton,1,8,1,1);

    m_treeWidget = new QTreeWidget;
    m_treeWidget->setAlternatingRowColors(true);

    //设定头项名称
    m_treeWidget->headerItem()->setText(0,QStringLiteral("均价单号"));
    m_treeWidget->headerItem()->setText(1,QStringLiteral("资金账号"));
    m_treeWidget->headerItem()->setText(2,QStringLiteral("合约"));
    m_treeWidget->headerItem()->setText(3,QStringLiteral("买卖"));
    m_treeWidget->headerItem()->setText(4,QStringLiteral("开平"));
    m_treeWidget->headerItem()->setText(5,QStringLiteral("套保标识"));
    m_treeWidget->headerItem()->setText(6,QStringLiteral("每次手数"));
    m_treeWidget->headerItem()->setText(7,QStringLiteral("总手数"));
    m_treeWidget->headerItem()->setText(8,QStringLiteral("时间间隔(秒)"));
    m_treeWidget->headerItem()->setText(9,QStringLiteral("状态"));
    m_treeWidget->headerItem()->setText(10,QStringLiteral("启用标识"));
    m_treeWidget->headerItem()->setText(11,QStringLiteral("委托时间"));
    m_treeWidget->headerItem()->setText(12,QStringLiteral("发送数量"));
    m_treeWidget->headerItem()->setText(13,QStringLiteral("成交数量"));
    m_treeWidget->headerItem()->setText(14,QStringLiteral("成交价格"));

    m_treeWidget->header()->setSectionsClickable(true);
    m_treeWidget->header()->setSectionsMovable(true);
    QFont font = m_treeWidget->header()->font();
    font.setBold(true);
    m_treeWidget->header()->setFont(font);

    m_treeWidget->setColumnCount(14);
    m_treeWidget->setColumnWidth(0,100);
    m_treeWidget->setColumnWidth(1,100);
    m_treeWidget->setColumnWidth(2,100);
    m_treeWidget->setColumnWidth(3,120);
    m_treeWidget->setColumnWidth(4,100);
    m_treeWidget->setColumnWidth(5,100);
    m_treeWidget->setColumnWidth(6,100);
    m_treeWidget->setColumnWidth(7,100);
    m_treeWidget->setColumnWidth(8,100);
    m_treeWidget->setColumnWidth(9,100);
    m_treeWidget->setColumnWidth(10,100);
    m_treeWidget->setColumnWidth(11,100);
    m_treeWidget->setColumnWidth(12,100);
    m_treeWidget->setColumnWidth(13,100);
    m_treeWidget->setColumnWidth(14,100);

    MainLayout = new QGridLayout(this);
    MainLayout->addLayout(layout,0,0);
    MainLayout->addWidget(m_treeWidget,1,0);
    MainLayout->setMargin(20);

	//创建菜单、菜单项
	/*this->m_tableBalance->setContextMenuPolicy(Qt::CustomContextMenu);
	m_RightPopMenu = new QMenu(this->m_tableBalance);
	QAction* updateAction = new QAction(QStringLiteral("刷新"),this);
	QAction* outputAction = new QAction(QStringLiteral("导出"),this); 
	m_RightPopMenu->addAction(updateAction);
	m_RightPopMenu->addAction(outputAction);
    //右键弹出菜单事件绑定
	connect(this->m_tableBalance,SIGNAL(customContextMenuRequested(const QPoint&)),this,SLOT(RightClickedMenuPop(const QPoint&)));*/
    connect(this->m_ConfirmButton,SIGNAL(clicked()),this,SLOT(OKButtonClicked()));
}
void MainAverageEntrustWidget::OKButtonClicked(){
    /*if(m_accountCombox->currentText() == ""){
        QMessageBox::critical(NULL,QString("ERROR"),QStringLiteral("请选择有效资金账号!"));
        return;
    }
    if(m_contractEdit->text() == ""){
        QMessageBox::critical(NULL,QString("ERROR"),QStringLiteral("请输入有效合约代码!"));
        return;
    }
    if(m_HandsSpinBox->text().toInt() == 0 || m_TotalHandsSpinBox->text().toInt() == 0){
        QMessageBox::critical(NULL,QString("ERROR"),QStringLiteral("请输入正确的手数信息!"));
        return;
    }
    if(m_timeEdit->text().toInt() == 0 ){
        QMessageBox::critical(NULL,QString("ERROR"),QStringLiteral("请输入正确的时间间隔!"));
        return;
    }

	AVERAGEORDERINFO typeOrder;
	strcpy_s(typeOrder.AccountID, m_accountCombox->currentText().toStdString().c_str());
	typeOrder.AveragePrice= 0;
	typeOrder.AverageStatus= 1;
	
	if (m_bsCombox->currentIndex() == 0){
		typeOrder.BS= 1;//买入
	}else{
		typeOrder.BS= 2;//卖出
	}
	strcpy_s(typeOrder.ContractID, m_contractEdit->text().toStdString().c_str());
	typeOrder.PerSendHands = m_HandsSpinBox->text().toInt();
	typeOrder.EnableStatus= 1;
	typeOrder.EntrustAmount= 0;
	typeOrder.iMsgType= 1;        //均价单

	if (m_ocCombox->currentIndex() == 0){
		typeOrder.OC = 1;//开仓
	}else if(m_ocCombox->currentIndex() == 1){
		typeOrder.OC = 2;//平仓
	}else{
		typeOrder.OC = 4;//平今仓
	}

	typeOrder.SendAmount= 0;
	typeOrder.TimeSpan= m_timeEdit->text().toInt();
	typeOrder.TotalAcount= m_TotalHandsSpinBox->text().toInt();
	typeOrder.TradeAmount= 0;
	if (m_OrderTypeCheckbox->isChecked()){
		typeOrder.Entrusttype = 2;//套保
	}else{
		typeOrder.Entrusttype = 1;
	}
	strcpy_s(typeOrder.UserID, m_accountCombox->currentText().toStdString().c_str());

    emit NewAverageOrder(typeOrder);*/
}

void MainAverageEntrustWidget::SelectContract(const QModelIndex & index){
    int iRow = index.row();
    //合约
    QModelIndex oContract = index.sibling(iRow,0);
    QString strContract = oContract.data().toString();
    this->m_contractEdit->setText(strContract);

    this->m_HandsSpinBox->setValue(0);
    this->m_TotalHandsSpinBox->setValue(0);
    this->m_timeEdit->setText("0");
}

void MainAverageEntrustWidget::ShowAverageOrder(int icnt, void* pData){
	//CString str, sStatus, sAccount;
    /*AVERAGEORDERINFO* pOrderInfo = (AVERAGEORDERINFO*)pData;
	for(int i = 0; i < icnt; i++)
	{
		//--存储到队列中--		
		QString strKey = QString::number(pOrderInfo[i].OrderID); 
		STAverageInfo stAverage;
		stAverage.var0_AverageNumber= QString::number(pOrderInfo[i].OrderID); 
		stAverage.var10_sStatus= ComFunc::GetCofcoStatusName(pOrderInfo[i].AverageStatus); 
		stAverage.var11_sRunStatus= "开启";	
		stAverage.var1_szAccount= QString(pOrderInfo[i].AccountID); 
		stAverage.var2_sContractCode= QString(pOrderInfo[i].ContractID); 
		stAverage.var3_sBsName= ComFunc::GetBSName( pOrderInfo[i].BS ); 
		stAverage.var4_sOcName= ComFunc::GetOCName( pOrderInfo[i].OC ); 		
		stAverage.var8_sHedge= ComFunc::GetHedgeType(pOrderInfo[i].Entrusttype-1);  //投机套保，特殊处理一下		
		//stAverage.var15_sEntrustTime= CComFun::FormatCS(pOrderInfo[i].EntrustTime);   //取本地时间
		stAverage.var15_sEntrustTime= ComFunc::GetCurrTime(); 
		stAverage.var16_sGapStatus= "开始";
		stAverage.var17_sEntrustType= "限价";
		stAverage.bRspBusiness= TRUE;
		stAverage.bRspEntrust= TRUE;
		stAverage.bRspOrder=TRUE;

		stAverage.EachHand= pOrderInfo[i].PerSendHands; 
		stAverage.TotalHand= pOrderInfo[i].TotalAcount; 
		stAverage.TimeSpin= pOrderInfo[i].TimeSpan; 
		stAverage.SendHand= pOrderInfo[i].SendAmount; 
		stAverage.BusinessHand= pOrderInfo[i].TradeAmount; 
		stAverage.BussPrice= pOrderInfo[i].AveragePrice; 

		stAverage.UpPrice= 0; 
		stAverage.DownPrice= 0;

		m_MapAverageOrder[strKey] = stAverage;
		//显示在控件上	
		QStringList Items;
		Items<<stAverage.var0_AverageNumber<<stAverage.var1_szAccount<<stAverage.var2_sContractCode<<stAverage.var3_sBsName<<stAverage.var4_sOcName;
		QTreeWidgetItem* A = new QTreeWidgetItem(Items);
		m_treeWidget->addTopLevelItem(A);  
		//添加子节点
		for(int i=0; i<3; ++i)  
		{  
			QStringList columItemList;  
			QTreeWidgetItem *child;  
			QString key, value;  
			key += "a" + QString::number(i);  
			value += QString::number(i);  
			columItemList<<key<<value;  
			child = new QTreeWidgetItem(columItemList);  
			A->addChild(child);  
		}
		//开启定时器
		SetIfTimer(strKey);
    }*/
}

void MainAverageEntrustWidget::SetIfTimer(QString AverageNo)
{
	QMap<QString, STAverageInfo>::iterator itrAvg;	
	itrAvg = m_MapAverageOrder.find(AverageNo);
	if (itrAvg != m_MapAverageOrder.end())
	{
		int iTime= itrAvg->TimeSpin*1000;
		emit SigStartTimer(AverageNo,iTime);
	}
}

void MainAverageEntrustWidget::timerEvent(QTimerEvent *e)
{
	int timerid = e->timerId();
	QString AverageNo = m_MapTimerID[timerid];
	
	QMap<QString, STAverageInfo>::iterator itrAvg;	

	itrAvg = m_MapAverageOrder.find(AverageNo);
	if (itrAvg != m_MapAverageOrder.end()){
		//获取交易所信息
		/*CString sExchange;
		sExchange= theApp.m_pDataService->GetContractExch(itrAvg->second.var2_sContractCode);	
		if (sExchange=="")   
		{
			CComFun::ShowMessage("获取不到交易所信息，下单失败1！");
			return;
		}
		CString csLog;
		csLog.Format(_T("Timer:[Gapstatus=%s; bRspBusiness=%d, bRspEntrust=%d, sEntrustType=%s"),
			itrAvg->second.var16_sGapStatus.GetString()
			, itrAvg->second.bRspBusiness
			, itrAvg->second.bRspEntrust
			, itrAvg->second.var17_sEntrustType.GetString()
			);
		theApp.LogMessage(csLog);*/
		//--判断条件-----
		//if ( theApp.ChectIfOpenMarket(sExchange) ){
			if (itrAvg->var16_sGapStatus=="开始"){
                //SendOneOrderOfAvg(AverageNo);
			}else if (itrAvg->var16_sGapStatus=="委托"){
				if ((itrAvg->bRspBusiness) && (itrAvg->bRspEntrust) && (itrAvg->bRspOrder)){
					if (itrAvg->var17_sEntrustType=="限价"){
						itrAvg->var16_sGapStatus="开始";
					}else{
                    //	SendOneOrderOfAvg(AverageNo);
					}
				}else if ((!itrAvg->bRspBusiness) && (itrAvg->bRspEntrust) && (itrAvg->bRspOrder)){
					//--委托状态，撤单，下单
					//WithdrawEntrustDataFromMap(itrAvg->var1_szAccount, itrAvg->var18_sEntrustNo);
                    //SendOneOrderOfAvg(AverageNo);
				}
			}
		//}			
	}
}

void MainAverageEntrustWidget::SlotStartTimer(QString AverageNo,int iTimeSpan){
	int timerID = QObject::startTimer(iTimeSpan,Qt::CoarseTimer);

	m_MapTimerID.insert(timerID,AverageNo);//将TimerID与均价单的编号存入Map中，建立对应关系
}
